import 'dart:convert';
import 'dart:io';
import 'package:file_selector/file_selector.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_client_sse/constants/sse_request_type_enum.dart';
import 'package:flutter_client_sse/flutter_client_sse.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:windows_demo/Utils/color_utils.dart';

import '../Utils/DB/MessageDao.dart';
import '../Widgets/ChatBar.dart';
import 'DouBao.dart';
import 'MessageModel.dart';

class Chat extends StatefulWidget {
  const Chat({super.key,});

  @override
  State<Chat> createState() => _ChatState();
}

class _ChatState extends State<Chat> {
  // 聊天历史最小宽度
  double historyMinWidth = 200;
  // 聊天历史缓存宽度 解决当滑动超过范围时回调会直接触发，而不是到边缘值触发的问题
  double historyCacheWidth = 0;
  // 聊天历史当前宽度
  late double historyWidth;
  // 编辑区域最小高度
  double editAreaMinHeight = 100;
  // 编辑区域缓存高度
  double editCacheHeight = 0;
  // 编辑区域当前高度
  late double editAreaHeight;

  List chatItemsInfo = [
    ChatItemInfo(
      label: '刘克',
      icon: 'assets/images/people.png',
    ),
    ChatItemInfo(
      label: '陈文发',
      icon: 'assets/images/people.png',
    ),
    ChatItemInfo(
      label: '谢嘉豪',
      icon: 'assets/images/people.png',
    ),
  ];

  // 消息
  List<MessageModel> messages = [];
  String imagePath = '';
  // 是否正在回答
  bool isAnswering = false;

  int selectedIndex = 0;
  final TextEditingController textEditingController = TextEditingController();
  final FocusNode focusNode = FocusNode();

  final controlEnter = const SingleActivator(
    LogicalKeyboardKey.enter,
    control: true,
  );
  final enter = const SingleActivator(
    LogicalKeyboardKey.enter,
  );
  final enter1 = const SingleActivator(
    LogicalKeyboardKey.enter,
    shift: true,
  );
  final enter2 = const SingleActivator(
    LogicalKeyboardKey.enter,
    alt: true,
  );
  final enter3 = const SingleActivator(
    LogicalKeyboardKey.enter,
    meta: true,
  );

  @override
  void initState() {
    super.initState();
    // 初始化时默认最小
    historyWidth = historyMinWidth;
    editAreaHeight = editAreaMinHeight;
    getLocalMessageCopy();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          return Row(
            children: [
              // 聊天列表
              Container(
                width: historyWidth,
                color: YZMColors.transparent,
                child: ChatBar(
                  chatItemsInfo: chatItemsInfo,
                  selectedIndex: selectedIndex,
                  onSelect: (index) {
                    setState(() {
                      selectedIndex = index;
                    });
                  },
                  onDelete: (index) {
                    setState(() {
                      chatItemsInfo.removeAt(index);
                    });
                  },
                  hoveringColor: YZMColors.color_99_20,
                ),
              ),
              GestureDetector(
                onHorizontalDragStart: (value) {
                  historyCacheWidth = historyWidth;
                },
                // 监听水平方向的拖拽操作
                onHorizontalDragUpdate: (details) {
                  // 获取拖拽的距离
                  double delta = details.delta.dx;
                  // 更新左边的组件的宽度
                  historyCacheWidth += delta;
                  historyWidth = historyCacheWidth;
                  // 限制左边的组件的宽度在 0 到屏幕宽度之间
                  historyWidth = historyWidth.clamp(historyMinWidth, constraints.maxWidth/2);
                  // 重绘组件
                  setState(() {});
                },
                child: const MouseRegion(
                  cursor: SystemMouseCursors.resizeColumn,
                  child: VerticalDivider(
                    width: 4,
                    thickness: 2,
                    color: YZMColors.color_99,
                  ),
                ),
              ),
              // 使用 Expanded 组件来包裹右边的组件
              Expanded(
                child: Column(
                  children: [
                    Expanded(
                      child: DouBao(
                        messages: messages,
                        isAnswering: isAnswering,
                      ),
                    ),
                    GestureDetector(
                      onVerticalDragStart: (value) {
                        editCacheHeight = editAreaHeight;
                      },
                      onVerticalDragUpdate: (details) {
                        double y = details.delta.dy;
                        editCacheHeight -= y;
                        editAreaHeight = editCacheHeight;
                        editAreaHeight = editAreaHeight.clamp(editAreaMinHeight, constraints.maxHeight/2);
                        // 重绘组件
                        setState(() {});
                      },
                      child: const MouseRegion(
                        cursor: SystemMouseCursors.resizeRow,
                        child: Divider(
                          height: 4,
                          thickness: 2,
                          color: YZMColors.color_99,
                        ),
                      ),
                    ),
                    Container(
                      padding: const EdgeInsets.all(8),
                      height: editAreaHeight,
                      child: Column(
                        children: [
                          Expanded(
                            child: Shortcuts(
                              shortcuts: {
                                enter : const SendMessageIntent(),
                                enter1 : const SendMessageIntent(),
                                enter2 : const SendMessageIntent(),
                                enter3 : const SendMessageIntent(),
                                controlEnter: const NewLineIntent(),
                              },
                              child: Actions(
                                actions: <Type, Action<Intent>>{
                                  SendMessageIntent: CallbackAction<SendMessageIntent>(onInvoke: (intent) {
                                    sendMessage();
                                    return null;
                                  }),
                                  NewLineIntent: CallbackAction<NewLineIntent>(onInvoke: (intent) {
                                    textEditingController.text += '\n';
                                    return null;
                                  }),
                                },
                                child: TextField(
                                  focusNode: focusNode,
                                  maxLines: null,
                                  minLines: 1,
                                  controller: textEditingController,
                                  decoration: const InputDecoration(
                                    border: InputBorder.none,
                                    isCollapsed: true,
                                    counterText: '',
                                  ),
                                  style: const TextStyle(
                                    fontSize: 16,
                                    color: YZMColors.color_black,
                                  ),
                                  cursorColor: YZMColors.color_black,
                                  keyboardType: TextInputType.multiline,
                                  onChanged: (value) {
                                    setState(() {});
                                  },
                                ),
                              ),
                            ),
                          ),
                          Row(
                            children: [
                              const Expanded(child: SizedBox.shrink()),
                              const Text('Enter发送,Ctrl+Enter换行'),
                              const SizedBox(width: 12),
                              Builder(
                                builder: (context) {
                                  String text = textEditingController.text;
                                  bool isEmpty = (text.isEmpty || text.trim().isEmpty || isAnswering) && imagePath.isEmpty;
                                  return IgnorePointer(
                                    ignoring: isEmpty,
                                    child: TextButton(
                                      style: ButtonStyle(
                                        backgroundColor: MaterialStatePropertyAll(isEmpty ? YZMColors.color_primary_40 : YZMColors.color_primary_80),
                                        overlayColor: const MaterialStatePropertyAll(YZMColors.color_primary),
                                        shape: MaterialStateProperty.all(
                                          RoundedRectangleBorder(
                                            borderRadius: BorderRadius.circular(4),
                                          ),
                                        ),
                                      ),
                                      onPressed: () {
                                        sendMessage();
                                      },
                                      child: const Text(
                                        '发送',
                                        style: TextStyle(
                                          color: YZMColors.color_white,
                                        ),
                                      ),
                                    ),
                                  );
                                },
                              ),
                              const SizedBox(width: 12),
                              TextButton(
                                style: ButtonStyle(
                                  backgroundColor: const MaterialStatePropertyAll(YZMColors.color_primary_80),
                                  overlayColor: const MaterialStatePropertyAll(YZMColors.color_primary),
                                  shape: MaterialStateProperty.all(
                                    RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(4),
                                    ),
                                  ),
                                ),
                                onPressed: () async {
                                  const xType = XTypeGroup(label: '图片', extensions: ['jpg', 'png']);
                                  openFile(acceptedTypeGroups: [xType]).then((value) {
                                    if (value != null) {
                                      setState(() {
                                        imagePath = value.path;
                                      });
                                    }
                                  });
                                },
                                child: const Text(
                                  '上传图片',
                                  style: TextStyle(
                                    color: YZMColors.color_white,
                                  ),
                                ),
                              ),
                              imagePath.isEmpty ? const SizedBox.shrink() : Container(
                                margin: const EdgeInsets.only(left: 12),
                                child: GestureDetector(
                                  onTap: () {
                                    setState(() {
                                      imagePath = '';
                                    });
                                  },
                                  child: Image.file(
                                    File(imagePath),
                                    width: 30,
                                    height: 30,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  sendMessage() async {
    String text = textEditingController.text;
    if ((text.isEmpty || text.trim().isEmpty || isAnswering) && imagePath.isEmpty) return;
    MessageModel userMessage = MessageModel(id: 0, messageContent: '', isUser: 0);
    userMessage.id = DateTime.now().millisecondsSinceEpoch;
    userMessage.messageContent = textEditingController.text;
    userMessage.isUser = 1;
    setState(() {
      messages.insert(0,userMessage);
    });
    setLocalMessageCopy(userMessage);

    Map<String,dynamic> params = {};
    params['model'] = 'ep-20241220135958-2rlv4';
    List<Map<String,dynamic>> requestMessages = [];


    List content = [];
    content.add({
      'type': 'text',
      'text': textEditingController.text,
    });
    if (imagePath.isNotEmpty) {
      String imageBytes = base64Encode(await File(imagePath).readAsBytes());
      content.add({
        'type': 'image_url',
        'image_url': {
          'url': 'data:image/jpeg;base64,$imageBytes'
        },
      });
      imagePath = '';
    }

    requestMessages.add({
      'role': 'user',
      'content': content,
    });
    requestMessages.add({
      'role': 'system',
      'content': '如果你接受到了图片信息，无论我有没有给你文本信息，你都要直接给我描述图片的内容',
    });
    params['messages'] = requestMessages;
    params['stream'] = true;

    textEditingController.clear();

    /// 流式调用
    MessageModel sysMessage = MessageModel(id: 0, messageContent: '', isUser: 0);
    setState(() {
      messages.insert(0,sysMessage);
      isAnswering = true;
    });
    SSEClient.subscribeToSSE(
      method: SSERequestType.POST,
      url:'https://ark.cn-beijing.volces.com/api/v3/chat/completions',
      header: {
        "Authorization":'Bearer 5c847c21-466f-4f81-b07d-984d8c308e42',
      },
      body: params,
    ).listen((event) {
      if (event.data != null) {
        dynamic data;
        try {
          data = jsonDecode(event.data!);
        } catch (e) {
          return;
        }

        if (data!['choices'][0]['finish_reason'] == 'stop') {
          messages[0].id = DateTime.now().millisecondsSinceEpoch;
          setLocalMessageCopy(messages[0]);
          setState(() {
            isAnswering = false;
          });
          return;
        }

        setState(() {
          messages[0].messageContent += data!['choices'][0]['delta']['content'];
        });
      } else {
        SmartDialog.showToast('获取信息异常',displayType: SmartToastType.last);
        setState(() {
          isAnswering = false;
        });
      }
    });
  }

  /// 存储数据库
  getLocalMessageCopy() async {
    List<MessageModel> localMessages = await MessageDao.queryAll();
    setState(() {
      messages = localMessages.reversed.toList();
    });
  }

  setLocalMessageCopy(MessageModel messageModel) async {
    bool isExist = await MessageDao.isExist(messageModel.id);
    if(!isExist){
      int flag = await MessageDao.insert(messageModel);
      if (flag <= 0) {
        SmartDialog.showToast('写入失败',displayType: SmartToastType.last);
      }
    }else{
      SmartDialog.showToast('主键重复',displayType: SmartToastType.last);

    }
  }


}

// Enter 发送
class SendMessageIntent extends Intent {
  const SendMessageIntent();
}
// Ctrl+Enter 换行
class NewLineIntent extends Intent {
  const NewLineIntent();
}